import React, { useCallback } from 'react';
import { LogoutOutlined } from '@ant-design/icons';
import { Avatar, Menu, Spin } from 'antd';
import { history, useModel } from 'umi';
import HeaderDropdown from '@/chaos/components/HeaderDropdown';
import styles from './index.less';
import { submit } from '@/chaos/functions/Data';

export type GlobalHeaderRightProps = { menu?: boolean };

const loginOut = async () => {
    await submit('logout');
    history.replace('/');
};

const AvatarDropdown: React.FC<GlobalHeaderRightProps> = () => {
    const { initialState, setInitialState } = useModel<any>('@@initialState');

    const onMenuClick: any = useCallback(
        (event: {
            key: React.Key;
            keyPath: React.Key[];
            item: React.ReactInstance;
            domEvent: React.MouseEvent<HTMLElement>;
        }) => {
            const { key } = event;
            if (key === 'logout' && initialState) {
                setInitialState({ ...initialState, currentUser: undefined });
                loginOut();
                return;
            }
            history.push(`/account/${key}`);
        },
        [initialState, setInitialState],
    );

    const loading = (
        <span className={`${styles.action} ${styles.account}`}>
            <Spin size="small" style={{ marginLeft: 8, marginRight: 8 }} />
        </span>
    );

    if (!initialState) {
        return loading;
    }

    const { currentUser } = initialState;

    if (!currentUser || !currentUser.mu) {
        return loading;
    }

    const menuHeaderDropdown = (
        <Menu className={styles.menu} selectedKeys={[]} onClick={onMenuClick}>
            <Menu.Item key="logout">
                <LogoutOutlined />
                退出登录
            </Menu.Item>
        </Menu>
    );
    return (
        <HeaderDropdown overlay={menuHeaderDropdown}>
            <span className={`${styles.action} ${styles.account}`}>
                <Avatar size="small" className={styles.avatar} src={currentUser.avatar} />
                <span className={`${styles.name} anticon`}>{currentUser.name}</span>
            </span>
        </HeaderDropdown>
    );
};

export default AvatarDropdown;
